package main

import (
	"context"
	"log"
	"net/http"

	"github.com/golang/glog"
	"golang.org/x/sync/errgroup"

	"golang-training-camp/src/week3/service"
)

func main() {
	g, ctx := errgroup.WithContext(context.Background())

	mux := http.NewServeMux()
	mux.HandleFunc("/hello", service.Hello)

	// 模拟单个服务错误退出
	service.CrashChan = make(chan struct{})
	mux.HandleFunc("/crash", service.Crash)

	server := http.Server{
		Handler: mux,
		Addr:    ":8080",
	}

	g.Go(func() error {
		glog.Infof("Http server has start on %v", server.Addr)
		return server.ListenAndServe()
	})

	g.Go(func() error {
		select {
		case <-ctx.Done():
			glog.Info("Errgroup exit.")
		case <-service.CrashChan:
			glog.Info("CrashChan exit.")
		}

		glog.Info("Shutting down server.")
		return server.Shutdown(ctx)
	})

	err := g.Wait()
	if err != nil {
		log.Fatal("Errgroup has error ", err)
	}
}
